<template>
  <div class="order-apply-invoice">
    <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, watch, nextTick, ref, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

// 定义点击事件发射器
const emits = defineEmits<{
  (e: 'dataPointClick', params: any): void
}>()

const props = defineProps({
  config: {
    type: Object,
    required: true,
    default: () => ({
      xAxisData: [],
      yAxisData: [],
      legendData:[]
    })
  }
})

const chartContainer = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return
  
  // 销毁旧实例
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  chartInstance = echarts.init(chartContainer.value)
  updateChart()
  if (!chartInstance) return
  
  // 监听数据点点击事件
  chartInstance.on('click', 'series.line', (params: any) => {
    emits('dataPointClick', params)
  })
}

// // 设置数据点点击事件
// const setupDataPointClickEvent = () => {
//   if (!chartInstance) return
  
//   // 监听数据点点击事件
//   chartInstance.on('click', 'series.line', (params: any) => {
//     console.log('数据点被点击:', params)
//     emits('dataPointClick', params)
//   })
// }
// 更新图表配置
const updateChart = () => {
  if (!chartInstance) return
  
  const option = {
    legend: {
        right: '50px',
        top: '20px',
        data: [props.config.legendData[0] || '已提箱量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Array.from(props.config.xAxisData) // 使用展开运算符创建新数组
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: props.config.legendData[0] || '已提箱量',
        data: Array.from(props.config.yAxisData),
        type: 'line',
        smooth: true, // 添加平滑效果
        itemStyle: {
          color: '#5470C6' // 设置线条颜色
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
            { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
          ])
        },
        label: {
          show: true, // 显示标签
          position: 'top',
          formatter: '{c}个', // 显示数据值
        }
      }
    ],
    tooltip: {
      trigger: 'axis'
    }
  }
  
  chartInstance.setOption(option)

}

// 组件卸载时清理
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 监听props变化
watch(
  () => props.config,
  () => {
    nextTick(updateChart)
  },
  { deep: true }
)

// 初始化
onMounted(() => {
  nextTick(initChart)
})
</script>

<style lang="scss" scoped>
.order-apply-invoice {
  // 可以添加一些样式
}
</style>